﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "database_home.h"
#include <QDesktopWidget>
//#define chosedtable;
QStringList tablelist,canshulist;
bool parentNodeSelected=false;
QVector<double> x(1000),y(1000);
QString login::userType;
QMap<QString, QString> columnNameMap;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    Init();
    this->window()->setWindowState(Qt::WindowMaximized);
    // 初始化中英文列名
    QList<QPair<QString, QString>> columnNameList({
        {"id", "id"},
        {"Test", "一般信息"},
        {"Content", "值"},
        {"Time", "时间(s)"},
        {"O2", "氧气(%)"},
        {"DPT", "孔板处压差(Pa)"},
        {"CO", "一氧化碳(%)"},
        {"CO2", "二氧化碳(%)"},
        {"PDM", "主感光器(-)"},
        {"PDC", "补偿感光器(-)"},
        {"Mass", "试样质量(g)"},
        {"Methane_MFM", "甲烷质量流速(slpm)"},
        {"APT", "环境大气压(kPa)"},
        {"HFM", "热流量(kW/㎡)"},
        {"Cold_Trap_TC", "冷井温度(K)"},
        {"Stack_TC", "Stack处温度(K)"},
        {"Smoke_TC", "烟气温度(K)"},
        {"Cone_Heater_TC", "锥形加热器温度(K)"},
        {"Spare_TC", "备用热电偶测得温度(K)"},
        {"Soot_MFM", "烟灰质量流速(g/s)"},
        {"AFM", "采样气流量(l/min)"},
        {"HRR", "热释放率(kW/㎡)"},
        {"EHC", "有效燃烧热(MJ/kg)"},
        {"SEA", "比消光面积 (m2/kg)"},
        {"MLR", "质量损失速率(g/s)"},
        {"SpecificMLR", "单位面积的质量损失速率(g/(s•㎡))"},
        {"COY", "CO生成量 (kg/kg)"},
        {"CO2Y", "CO2生成量 (kg/kg)"},
        {"THR", "总热释放(MJ/㎡)"},
        {"MFR", "质量流量 (g/s)"},
        {"k", "k系数 (1/m)"},
        {"Vstack", "stack处烟气体积流速 (l/s)"},
        {"Vsmoke", "smoke处烟气体积流速 (l/s)"},
        {"SPR", "产烟速率 (㎡/s)"},
        {"RSR", "单位面积产烟速率((㎡/s)/㎡)"},
        {"TSP", "总产烟量(㎡)"},
        {"TSR", "单位面积总产烟量 (㎡/㎡)"},
        {"COP", "CO生成速率(g/s)"},
        {"CO2P", "CO2生成速率(g/s)"},
        {"O2C", "耗氧速率(g/s)"},
        {"TOC", "总耗氧量(g)"},
        {"ARHE", "平均热释放速率(kW/㎡)"},
        {"Specimenmass", "样品质量(g)"},
        {"Oxygen", "空气氧浓度 (%)"},
        {"DPT", "孔板处压差 (Pa)"},
        {"CO", "空气CO浓度 (%)"},
        {"CO2", "空气CO2浓度 (%)"},
        {"ColdTrapTC", "冷井温度(K)"},
        {"StackTC", "stack处温度(K)"},
        {"SmokeTC", "smoke处温度(K)"},
        {"ConeHeaterTC", "加热器温度(K)"},
        {"SootMFM", "烟灰质量流速(g/s)"},
        {"SpareTC", "备用热电偶测得温度 (K)"},
        {"HFM", "热流量(kW/㎡)"},
    });
    for (const QPair<QString, QString>& pair : columnNameList) {
        columnNameMap.insert(pair.first, pair.second);
    }
    //connect(ui->pushButton_home,&QPushButton::clicked,this,&MainWindow::on_home_clicked);
    //MySQL
    dbMYSQL=QSqlDatabase::addDatabase("QMYSQL");//创建数据库对象
    dbMYSQL.setHostName("localhost"); //为本机的 IP
    dbMYSQL.setPort(3306); //端口号，一般数据库都为 3306
    dbMYSQL.setDatabaseName("xfcl"); //自己设的数据库名
    dbMYSQL.setUserName("root"); //登录用户名 在创建数据库时设置的用户名和密码
    dbMYSQL.setPassword("123456"); //登录密码
    dbMYSQL.setConnectOptions("MYSQL_CHARSET=utf8mb4"); // 设置连接字符集为 utf8mb4
    if(!dbMYSQL.open())
    {
        QMessageBox::warning(this,"打开MySQL数据库失败",dbMYSQL.lastError().text());
    }
    else
    {
        qDebug()<<"打开MySQL数据库成功";
    }

    QObject::connect(ui->treeWidget,&QTreeWidget::itemClicked,this,&::MainWindow::treeWidgetClicked);
//    connect(ui->horizontalScrollBar, SIGNAL(valueChanged(int)), this,SLOT(on_horizontalScrollBar_valueChanged(int)));
//    connect(ui->verticalScrollBar, SIGNAL(valueChanged(int)), this,SLOT(on_verticalScrollBar_valueChanged(int)));
    // 连接QCustomPlot的信号，selectionChangedByUser表明是由鼠标点击进行的选择
    // 这里主要就是同步图表和图例的显示
    connect(ui->customPlot, &QCustomPlot::selectionChangedByUser, this,&MainWindow::selectedShow);
    connect(ui->customPlot, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuRequest(QPoint)));
    // 连接鼠标移动事件到槽函数
    connect(ui->customPlot, &QCustomPlot::mouseMove, this, &MainWindow::showPointToolTip);

//全选用的model
    mymodel = new QSqlTableModel(this,dbMYSQL);
//    mymodel->setTable("shanmuban15");
//    mymodel->setEditStrategy(QSqlTableModel::OnManualSubmit);
//    mymodel->select();
    model = new QStandardItemModel();//QStandardItemModel 是包含单元格的容器（在这里可以看作表）

    on_pushButton_query_clicked();  //显示所有表
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::Init()  //初始话treeview
{
    QStandardItemModel* model = new QStandardItemModel(ui->tableView);
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);//设置为不可修改
    ui->tableView->setModel(model);
    ui->treeWidget->setHeaderLabel("表格名");
//    ui->horizontalScrollBar->setRange(0,1000); //设置滑动条的范围
//    ui->verticalScrollBar->setRange(0,1000);
    ui->customPlot->xAxis->setLabel("time(s)");
//    ui->customPlot->axisRect()->setupFullAxesBox(true); //为每边画上刻度线，如果已经存在则将不执行
//    ui->customPlot->xAxis->setRange(0,1000,Qt::AlignLeft); //这句设置 x 轴显示范围
//    ui->customPlot->yAxis->setRange(0,40,Qt::AlignCenter);
    ui->customPlot->setMultiSelectModifier(Qt::ControlModifier);// 使用ctrl键来多选
    ui->customPlot->setContextMenuPolicy(Qt::CustomContextMenu);//自定义菜单
}

// 选中图例中的项，或者选中曲线时
void MainWindow::selectedShow()
{
    for (int i=0; i < ui->customPlot->graphCount(); ++i) {
        QCPGraph *graph = ui->customPlot->graph(i);
        QCPPlottableLegendItem *item = ui->customPlot->legend->itemWithPlottable(graph);//图例中的每一个项

        //选中图例中的项，或者选中曲线时，两者都被选中
        if (item->selected() || graph->selected())
        {
            graph->setSelected(true);// 当图例项被选择时，选择图表全部的数据
            item->setSelected(true);
        }
    }
    ui->customPlot->replot();   //刷新图表
}

// 设置显示/隐藏菜单
void MainWindow::contextMenuRequest(QPoint pos)
{
    QMenu *menu = new QMenu(this);
    menu->setAttribute(Qt::WA_DeleteOnClose);

    double legendCounts = ui->customPlot->legend->selectTest(pos, false);
    double graphCounts = ui->customPlot->graph()->selectTest(pos,false);

    //图例菜单
    if (( legendCounts >= 0) || ( graphCounts >= 0))
    {
        menu->addAction("显示", this, SLOT(showGraph()));
        menu->addAction("隐藏", this, SLOT(hideGraph()));
    }

    menu->popup(ui->customPlot->mapToGlobal(pos));

}
// 被选中的曲线显示
void MainWindow::showGraph()
{
    for (int i=0; i<ui->customPlot->graphCount(); ++i)
    {
        QCPGraph *graphItem = ui->customPlot->graph(i);

        if (graphItem->selected())
        {
            graphItem->setVisible(true);
        }
    }
    ui->customPlot->replot();
}

// 被选中的曲线隐藏
void MainWindow::hideGraph()
{
    for (int i=0; i< ui->customPlot->graphCount(); ++i)
    {
        QCPGraph *graphItem = ui->customPlot->graph(i);

        if (graphItem->selected())
        {
            qDebug() << graphItem->name();
            graphItem->setVisible(false);
        }
    }
    ui->customPlot->replot();
}

void MainWindow::draw(QString lineName,QVector<double> x,QVector<double> y,int lineNumber)
{
    QPen pen;
    ui->customPlot->addGraph();//每条曲线都会独占一个graph()
    pen.setColor(QColor(qSin(lineNumber*1+1.2)*80+80, qSin(lineNumber*0.3+0)*80+80, qSin(lineNumber*0.3+1.5)*80+80));
    ui->customPlot->graph()->setPen(pen);       // 设置画笔
    ui->customPlot->graph()->setName(lineName);//图例名称
    ui->customPlot->graph()->setLineStyle(QCPGraph::LineStyle::lsLine);  // 折线
    ui->customPlot->graph()->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 2));//设置散点形状
    ui->customPlot->legend->setVisible(true); // 显示图例
    ui->customPlot->graph()->setData(x, y);//x和y
    ui->customPlot->graph()->rescaleAxes(true);//自动调整XY轴的范围
//    ui->customPlot->xAxis->rescale();
    // 重新缩放Y轴
    ui->customPlot->graph()->rescaleValueAxis(false, true);
    // 支持鼠标拖拽轴的范围、滚动缩放轴的范围，左键点选图层（每条曲线独占一个图层）
    ui->customPlot->setInteractions(QCP::iRangeDrag |QCP::iRangeZoom | QCP::iSelectAxes | QCP::iSelectLegend | QCP::iSelectPlottables | QCP::iMultiSelect);

    ui->customPlot->replot();   //刷新图表
}

void MainWindow::showPointToolTip(QMouseEvent *event)
{
    // 获取鼠标当前位置（相对于 QCustomPlot）
    double x = ui->customPlot->xAxis->pixelToCoord(event->pos().x());
    double y = ui->customPlot->yAxis->pixelToCoord(event->pos().y());

    // 初始化变量
    bool ok = false;
    double closestX = 0, closestY = 0;
    double minDistance = std::numeric_limits<double>::max();
    QString graphName;

    // 遍历所有图表（graph），查找最近的数据点
    for (int g = 0; g < ui->customPlot->graphCount(); ++g) {
        QCPGraph *graph = ui->customPlot->graph(g);
        if (!graph || graph->data()->isEmpty()) continue;

        // 遍历数据点
        for (auto it = graph->data()->constBegin(); it != graph->data()->constEnd(); ++it) {
            double key = it.key();
            double value = it.value().value;

            // 计算鼠标与数据点的距离
            double distance = qSqrt(qPow(x - key, 5) + qPow(y - value, 5));
            if (distance < 0.5 && distance < minDistance) { // 设置距离阈值
                closestX = key;
                closestY = value;
                minDistance = distance;
                graphName = graph->name();  // 获取当前图表名称（需提前设置）
                ok = true;
            }
        }
    }

    if (ok) {
        // 显示数据点信息，包括图表名称或编号
        QString text = QString("Graph: %1\nX: %2\nY: %3").arg(graphName).arg(closestX).arg(closestY);
        QToolTip::showText(event->globalPos(), text, ui->customPlot);
    } else {
        // 隐藏提示
        QToolTip::hideText();
    }
}



// y轴滑块，废弃
void MainWindow::on_verticalScrollBar_valueChanged(int value)
{
    if (qAbs(ui->customPlot->yAxis->range().center()+value/100.0) > 0.01)
    {
        ui->customPlot->yAxis->setRange(-value/100.0, ui->customPlot->yAxis->range().size(), Qt::AlignCenter);
        ui->customPlot->replot();
    }
}
// x轴滑块，废弃
void MainWindow::on_horizontalScrollBar_valueChanged(int value)
{
    if (qAbs(ui->customPlot->xAxis->range().center()-value/100.0) > 0.01)
    {
        ui->customPlot->xAxis->setRange(value/100.0, ui->customPlot->xAxis->range().size(), Qt::AlignCenter);
        ui->customPlot->replot();
    }
}




//查询数据
void MainWindow::on_pushButton_query_clicked()
{
    tablelist.clear();
    canshulist.clear();
    ui->treeWidget->clear();

    QString cmd = "show tables;";//显示所有表
    QSqlQuery query(dbMYSQL);
    query.exec(cmd);

    tablecount=0;//目前表的数量
    //获取所有表名，并添加顶层结点
    while (query.next())
    {
        QString biaoming=query.value(0).toString().trimmed();
        tablelist<<biaoming;
        tablecount++;
        qDebug() << "table name:" << biaoming;//打印表名
        QTreeWidgetItem *item = new QTreeWidgetItem();
        item->setText(0,query.value(0).toString());//设置顶层结点
        item->setCheckState(0,Qt::Unchecked);//默认未选中
        ui->treeWidget->addTopLevelItem(item);

        //设置子节点
        QString selectsql="show columns from `%1`";
        QSqlQuery selectquery(dbMYSQL);
        //selectquery.exec(selectsql.arg(biaoming));
        if (!selectquery.exec(selectsql.arg(biaoming))) {
            // 处理错误
            qDebug() << "Error:" << query.lastError().text();
        }
        while(selectquery.next())
        {
            QString canshu=selectquery.value(0).toString();
            QString chineseColumnName = columnNameMap.value(canshu);
            if(canshu!="")
            {
                canshulist<<canshu;//添加项
                qDebug() <<"参数名为"<<canshu << chineseColumnName;
                QTreeWidgetItem *childitem=new QTreeWidgetItem(item, !chineseColumnName.isEmpty() ? QStringList(chineseColumnName) : QStringList(canshu));
                childitem->setCheckState(0,Qt::Unchecked);
            }
            canshulist.clear();
        }
    }
    qDebug() <<"@@@@@@@@@@@@@@@@@表名为"<<tablelist;
    qDebug() <<"！！！！！！！！！！参数名为"<<canshulist;
}




//接收 itemClicked() 信号函数传递过来的 item 参数
void MainWindow::treeWidgetClicked(QTreeWidgetItem *item)
{
    //QString filtername=item->text(0).trimmed();//节点名，子节点时为参数名,父节点时为表格名

    QString itemText = item->text(0);
       if (item->checkState(0) == Qt::Checked)
       {
           //QTreeWidgetItem *parent = item->parent();
           int cnt = item->childCount();
           if (cnt >0)
           {
               for (int i = 0;i < cnt;i++)
               {
                   item->child(i)->setCheckState(0,Qt::Checked);
               }
           }
           else
           {
               updateParentItem(item);
           }
       }
       else if (item->checkState(0) == Qt::Unchecked)
       {
           int cnt = item->childCount();
           if (cnt > 0)
           {
               for (int i = 0;i < cnt;i++)
               {
                   item->child(i)->setCheckState(0,Qt::Unchecked);
               }
           }
           else
           {
               updateParentItem(item);
           }
       }

    parentNodeSelected=false;

    parentNodeSelected=distinguishNodes(itemText);//判断是父节点还是子节点发生了变化
    if(parentNodeSelected)
        fatherNodeClicked(item,itemText);//父节点被点击，同步节点状态，显示整张表
    else{
        //遍历QMap，传入原始的字段名字
        QMapIterator<QString, QString> i(columnNameMap);
        while (i.hasNext())
        {
            i.next();
            if(i.value() == itemText){
                childrenNodeClicked(item,i.key());//子节点被点击，显示单列数据，取消点击，删除单列数据
            }
        }
    }

}


void MainWindow::updateParentItem(QTreeWidgetItem *item)
{
    QTreeWidgetItem *parent = item->parent();
    if (parent == NULL)
    {
        return;
    }
    //选中的子节点个数
    int selectedCount = 0;
    int childCount = parent->childCount();
    for (int i = 0; i < childCount; i++)
    {
        QTreeWidgetItem *childItem = parent->child(i);
        if (childItem->checkState(0) == Qt::Checked)
        {
            selectedCount++;
        }
    }
    if (selectedCount <= 0)
    {
        //未选中状态
        parent->setCheckState(0, Qt::Unchecked);
    }
    else if (selectedCount > 0 && selectedCount < childCount)
    {
        //部分选中状态
        parent->setCheckState(0, Qt::PartiallyChecked);
    }
    else if (selectedCount == childCount)
    {
        //选中状态
        parent->setCheckState(0, Qt::Checked);
    }
}

//判断是父节点还是子节点发生了变化
bool MainWindow::distinguishNodes(QString filtername)
{
    for(int i=0;i<tablelist.count();i++)
    {
        if(QString::compare(filtername,tablelist.at(i),Qt::CaseSensitive))//返回0表示相等
           ;
        else
        {           
            return true;
        }
    }
    return false;
}

//父节点被点击，同步节点状态，显示整张表
void MainWindow::fatherNodeClicked(QTreeWidgetItem* item ,QString filtername)
{
    lineNumber=0;
    ui->customPlot->clearGraphs();//清空所有曲线
    ui->customPlot->legend->setVisible(false);//取消图例
    ui->customPlot->replot();   //刷新图表
    setTableName = filtername;
    //遍历 item 结点所有的子结点，设置子父节点同状态
    for(int i=0;i<item->childCount();i++)
    {
        //找到每个子结点
        QTreeWidgetItem *childItem = item->child(i);
        //将子结点的选中状态调整为和父结点相同
        childItem->setCheckState(0,item->checkState(0));
    }

    if(item->checkState(0))//被选中，未选中为0，半选1，全选2
    {
        //父节点不能同时被选中
        for(int i=0 ; i < tablelist.count() ; i++ )
        {
            if(QString::compare(filtername,tablelist.at(i),Qt::CaseSensitive))//返回0表示相等，此处不同，同步父子节点状态
            {

                QList<QTreeWidgetItem *>  otheritems=ui->treeWidget->findItems(tablelist.at(i),Qt::MatchFixedString);
                otheritems.at(0)->setCheckState(0,Qt::Unchecked);
                for(int j=0 ; j < otheritems.at(0)->childCount() ; ++j )
                {
                    QTreeWidgetItem *cldItem = otheritems.at(0)->child(j);
                    cldItem->setCheckState(0,otheritems.at(0)->checkState(0));
                }
            }
            else
                ;

        }
        //显示整张表格
        //qDebug()<<"用户选择了父节点"<<filtername;
        //        mymodel->setTable(filtername);
        //        mymodel->select();
        //        ui->tableView->setModel(mymodel);
        model->clear();
        QString filtersql="select * from `%1`";//筛选结果
        QSqlQuery query(dbMYSQL);
        query.exec(filtersql.arg(filtername));
        QSqlRecord record = query.record();
        // 遍历查询结果
        while (query.next()) {
            QList<QStandardItem*> rowItems;
            for (int i = 0; i < record.count(); ++i) {
                QString value = query.value(i).toString();
                QStandardItem *item = new QStandardItem(value);
                rowItems.append(item);
            }
            model->appendRow(rowItems);
        }
        // 获取列名
        for (int i = 0; i < record.count(); ++i) {
            QString englishName = record.fieldName(i);
            QString chineseName = columnNameMap.value(englishName, englishName);
            model->setHeaderData(i, Qt::Horizontal, chineseName);
            ////qDebug()<<"column number: "<<i<<"column name: "<<record.fieldName(i);
        }
        //全选隐藏一二列
//        int columncount=model->columnCount();
//        qDebug() <<"当前有列："<<columncount;
//        for(int j = 0; j < columncount; j++)                // 遍历每一个单元格(列)
//        {
//            QVariant currenttext=model->headerData(j,Qt::Horizontal);
//            if(QString::compare(record.fieldName(0),currenttext.toString(),Qt::CaseSensitive));
//            else
//                model->takeColumn(j);
//        }
//        for(int j = 0; j < columncount; j++)                // 遍历每一个单元格(列)
//        {
//            QVariant currenttext=model->headerData(j,Qt::Horizontal);
//            if(QString::compare(record.fieldName(1),currenttext.toString(),Qt::CaseSensitive));
//            else
//                model->takeColumn(j);
//        }
//                model->takeColumn(0);
//                model->takeColumn(0);
        ui->tableView->setColumnHidden(0,true);//设置第0行隐藏
        ui->tableView->setColumnHidden(1,true);
        ui->tableView->setColumnHidden(2,true);
//      ui->tableView->horizontalHeader()->setStretchLastSection(true);//设置最后一列填充后面表格
        ui->tableView->setModel(model);
    }
    else//未选中
    {
        //清空tableview
        model->clear();
        ui->tableView->setModel(model);
    }
    // 手动调整列宽
    ui->tableView->resize(ui->tableView->width(), ui->tableView->height()); // 重新调整表格尺寸
//    ui->tableView->resizeColumnsToContents();
//    for (int i = 0; i < model->columnCount(); ++i) {
//        ui->tableView->setColumnWidth(i, qMax(ui->tableView->columnWidth(i), 100)); // 设置列宽至少为100像素
//    }

}


//子节点被点击，显示单列数据，取消点击，删除单列数据
void MainWindow::childrenNodeClicked(QTreeWidgetItem* item,QString filtername)
{
    int columncount=model->columnCount();
    qDebug()<< columncount;//当前列
    QString filtertable=item->parent()->text(0).trimmed();//子节点时为表格名
    setTableName = filtertable;

    bool jumpflag = false;
    for (int i = 0; i < model->columnCount(); i++)
    {
        QVariant currenttext = model->headerData(i, Qt::Horizontal);
        QString currentHeaderText = currenttext.toString().trimmed(); // 确保转换为 QString 并去除空格
        QString trimmedFilterName = columnNameMap.value(filtername.trimmed(), filtername.trimmed()); // 去除 filtername 的空格

        qDebug() << "Checking column" << i << "header:" << currentHeaderText << "against filtername:" << trimmedFilterName;

        if (trimmedFilterName.compare(currentHeaderText, Qt::CaseInsensitive) == 0 && item->checkState(0) == Qt::Checked)
        {
            jumpflag = true;
            qDebug() << "Match found! jumpflag set to true.";
            break; // 找到匹配后立即退出循环
        }
    }

    qDebug() << "Final jumpflag value:" << jumpflag;
    if(item->checkState(0) && jumpflag == false)    //选中状态
    {
        qDebug()<<"用户选择了子节点"<<filtername;
        QString filtersql="select `%1`.`%2` from `%1`";//筛选结果
        QSqlQuery filterquery(dbMYSQL);
        filterquery.exec(filtersql.arg(filtertable).arg(filtername));

        QVector<double> x(1000,0),y(1000,0);//绘图数据
        lineNumber++;//曲线数量
        int i=0,j=0;//向量角标
        QList<QStandardItem*> items;
        //y.clear();
        while(filterquery.next())
        {
            QString value = filterquery.value(0).toString();//单个数据值
            //qDebug() <<"单个数据值:"<<filterquery.value(0).toDouble();

            QStandardItem *item = new QStandardItem(value);//QStandardItem是存储数据的单元格，它存储的是QString
            items<<item;

            //y.append(filterquery.value(0).toDouble());//y轴数据
            y[i]=filterquery.value(0).toDouble();
            i++;
        }

        //对点击子节点的父节点的选中个数进行判断
        QTreeWidgetItem * parentItem = item->parent();
        int selectedCount = 0;
        int childCount = parentItem->childCount();
        for (int i = 0; i < childCount; i++)
        {
            QTreeWidgetItem *childItem = parentItem->child(i);
            if (childItem->checkState(0) == Qt::Checked)
            {
                if (childItem->text(0) != item->text(0))
                {
                    selectedCount++;
                }
            }
        }

        //如果点击另一个父节点的子节点，需要改变状态
        if(selectedCount == 0)
        {
            model->clear();//清除图表信息
            for(int i=0;i<tablelist.count();i++)
            {
                if(QString::compare(item->parent()->text(0),tablelist.at(i),Qt::CaseSensitive))//返回0表示相等
                {

                    QList<QTreeWidgetItem *>  otheritems=ui->treeWidget->findItems(tablelist.at(i),Qt::MatchFixedString);
                    otheritems.at(0)->setCheckState(0,Qt::Unchecked);
                    for(int j=0; j<otheritems.at(0)->childCount(); j++)
                    {
                        QTreeWidgetItem *cldItem = otheritems.at(0)->child(j);
                        cldItem->setCheckState(0,otheritems.at(0)->checkState(0));
                    }
                }
                else
                    ;
            }
        }

        // 检查列是否已经存在
        bool columnExists = false;
        for (int i = 0; i < model->columnCount(); i++)
        {
            QVariant currenttext = model->headerData(i, Qt::Horizontal);
            if (filtername == currenttext)
            {
                columnExists = true;
                break;
            }
        }

        // 如果列不存在，则插入列
        if (!columnExists)
        {
            model->insertColumn(selectedCount, items);
            // 设置表头
            QString chineseName = columnNameMap.value(filtername, filtername); // 获取中文列名
            model->setHorizontalHeaderItem(selectedCount, new QStandardItem(chineseName)); // 设置中文列头
            model->setHeaderData(selectedCount, Qt::Horizontal, chineseName); // 确保列头数据显示为中文

            // 获取x 时间轴数据
            filterquery.exec(filtersql.arg(filtertable).arg("Time"));
            qDebug() << filtersql.arg(filtertable).arg("Time");
            while (filterquery.next())
            {
                x[j] = filterquery.value(0).toDouble();
                // qDebug() <<"x["<<j<<"]="<<x[j];
                j++;
            }
            // 限制最大曲线数量
            if (lineNumber < 16)
                draw(chineseName, x, y, lineNumber); // 绘制一条曲线
            else
                QMessageBox::warning(this, tr("提示："), tr("曲线显示数量达到最大值"));
        }

    }
    else if(item->checkState(0) == Qt::Unchecked)//未被选中
    {
        //删除列
        int columncount=model->columnCount();
        qDebug() <<"当前有列："<<columncount;
        for(int j = 0; j < columncount; j++)                // 遍历每一个单元格(列)
        {
            QVariant currenttext=model->headerData(j,Qt::Horizontal);
            if(QString::compare(columnNameMap.value(filtername),currenttext.toString(),Qt::CaseSensitive))
                ;
            else
                model->takeColumn(j);
        }

        //清除曲线
        for (int i = 0; i < ui->customPlot->graphCount(); ++i) {
            if (ui->customPlot->graph(i)->name() == columnNameMap.value(filtername)) {
                ui->customPlot->removeGraph(i);
                lineNumber--;
                ui->customPlot->replot();
                break;
            }
        }
    }

    ui->tableView->setModel(model);//表视图，用于显示
    // 手动调整列宽
    ui->tableView->resize(ui->tableView->width(), ui->tableView->height()); // 重新调整表格尺寸
    //    ui->tableView->resizeColumnsToContents();
}



void MainWindow::on_pushButton_delete_clicked()
{
    if(login::userType!="User")
    {
        if(parentNodeSelected)
        {
            delete mymodel;
            mymodel = new QSqlTableModel(this,dbMYSQL);
            mymodel->setTable(setTableName);
            qDebug()<<"选中的表为："<<setTableName;
            int curRow = ui->tableView->currentIndex().row();
            //mymodel->removeRow(curRow);
            int ok = QMessageBox::warning(this,tr("提示："),"确定删除第"+QString::number(curRow+1)+"行吗？",QMessageBox::Yes,QMessageBox::No);
            if(ok == QMessageBox::No)
                //mymodel->revertAll(); //如果不删除，则撤销
                ;
            else{
                model->removeRow(curRow);
                mymodel->removeRow(curRow);
                if(!mymodel->submitAll())//否则提交，在数据库中删除该行
                {
                    qDebug()<<"更新数据库失败";
                }
                model->submit();
            }
        }
        else
        {
            QMessageBox::warning(this,tr("提示："),tr("多选状态下无法进行删除操作，请在全选状态下操作"));
        }
    }
    else
        QMessageBox::warning(this,tr("提示："),tr("您没有权限进行此操作"));
}



//搜索按钮
void MainWindow::on_toolButton_search_clicked()
{
    QString search = ui->lineEdit->text();
    QTreeWidgetItemIterator it(ui->treeWidget);
    qDebug()<<"search line:"<<search;
    while(*it)
    {
            if(QString::compare((*it)->text(0),search,Qt::CaseInsensitive))
            {
                 //不满足满足条件先隐藏，它的子项目满足条件时会再次让它显示
                qDebug()<<"search line:"<<search<<"compare item"<<(*it)->text(0);
                (*it)->setHidden(true);
            }
            else
            {
                (*it)->setHidden(false);
                QTreeWidgetItem *item = *it;
                //显示父节点
                while (item->parent())
                {
                    item->parent()->setHidden(false);
                    item = item->parent();
                 }
            }
            ++it;
    }
    ui->treeWidget->expandAll();
}

//导入按钮
void MainWindow::on_pushButton_import_clicked()
{
    QString filePath = QFileDialog::getOpenFileName(this, tr("Open Excel file"), "", tr("Excel Files (*.xlsx *.xls *.csv)"));//打开选择文件窗口
    if (!filePath.isEmpty())
    {
        qDebug() << "当前打开的文件路径为"<<filePath;//显示文件路径
    }
    QFileInfo fileInfo(filePath);
    QString baseName = fileInfo.completeBaseName(); // 获取不包含扩展名的文件名
    qDebug() << "去除扩展名后的文件名为：" << baseName;
    QSqlQuery query(dbMYSQL);
    bool red = false;
    QString txtFilePath = "";
    // 创建正则表达式对象，用于匹配包含"red"的文件名
    //QRegularExpression re(".*_red\\.CSV$");
    QRegularExpression re(".*_red\\.csv$", QRegularExpression::CaseInsensitiveOption);
    // 使用正则表达式匹配文件名
    QRegularExpressionMatch match = re.match(filePath);
    if (match.hasMatch()) {
        // 如果匹配成功，说明文件名包含"red"
        red = true;
        qDebug() << "这是red实验数据文件：" << filePath;
    } else {
        // 如果没有匹配成功，说明文件名不包含"red"
        qDebug() << "这是非red实验数据文件：" << filePath;
    }

    // 乱码处理部分
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "无法打开文件：" << filePath;
        return;
    }

    // 读取文件内容
    QTextStream in(&file);
    in.setCodec(QTextCodec::codecForName("utf-7"));
    QString content;
    QByteArray utf7Bytes = in.readAll().toLocal8Bit();
    std::string utf8String = utf7Bytes.toStdString();
    content.append(QString::fromUtf8(utf8String.c_str()));
    content.replace("\\", "\\\\");
    qDebug() << "csv内容: " << content;
    file.close();

    // 创建一个键值对映射，乱码字符串为键，正确字符串为值
    QMap<QString, QString> replacements {
        {"\\Surface area \\(cm\\s*\\b", "Surface area (c㎡)"},
        {"\\(kW/m\\s*\\b", "(kW/㎡)"},
        {"\\(\\?C\\)", "(℃)"},  // 捕捉潜在的乱码字符并替换
        {"\\(�C\\)", "(℃)"},    // 匹配并替换已知的乱码字符
        {"\\(g/m\\s*\\b","(g/㎡)"},
        {"\\(mkg\\)","(㎡/kg)"},  // 替换red乱码
        {"Total heat release \\(MJ/m","Total heat release (MJ/㎡)"},
        {"Average specific MLR \\(g/s\\?m","Average specific MLR (g/(s•㎡))"},
        {"Average specific MLR \\(g/s�m","Average specific MLR (g/(s•㎡))"},
        {"Total smoke release \\(mm\\s*\\b","Total smoke release (㎡/㎡)"},
        {"Total smoke production \\(m\\s*\\b","Total smoke production (㎡)"}
        // ... 添加更多的乱码和替换字符串对
    };

    // 遍历映射，替换所有的乱码字符串
    for (const auto &key : replacements.keys()) {
        content.replace(QRegularExpression(key), replacements[key]);
    }

    // 打开文件以写入模式，如果文件不存在则创建并写入内容
    QFile txtFile(baseName + ".txt");
    if (!txtFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
        qDebug() << "无法打开文件进行写入：" << baseName << ".txt";
        qDebug() << "错误信息：" << txtFile.errorString();
        return;
    }

    // 写入处理后的内容到.txt文件
    QTextStream outTxt(&txtFile);
    outTxt.setCodec(QTextCodec::codecForName("utf-8"));
    outTxt << content;
    txtFile.close();

    // 获取文件的绝对路径
    QFileInfo txtFileInfo(txtFile);
    txtFilePath = txtFileInfo.absoluteFilePath();

    qDebug() << "文件处理完成：" << txtFilePath;

    if(isTableExists(baseName))
    {
        int ok = QMessageBox::warning(this,tr("提示："),tr("当前数据库中已经存在该表，"
                                                        "确认替换吗？ "),QMessageBox::Yes,QMessageBox::No);
        if(ok == QMessageBox::No);//存在，不替换
        else  //存在，但替换
        {
            query.exec(QString("drop table if exists `%1`").arg(baseName));
            //creatNewTable();
            //InsertData();
            if(red){
                query.exec(QString("CREATE TABLE `%1` (id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,Test VARCHAR(255),Content VARCHAR(255),Time VARCHAR(20),HRR VARCHAR(255),EHC VARCHAR(255),SEA VARCHAR(255),MLR VARCHAR(255),SpecificMLR VARCHAR(255),COY VARCHAR(255),CO2Y VARCHAR(255),THR VARCHAR(255),MFR VARCHAR(255),k VARCHAR(255),Vstack VARCHAR(255),Vsmoke VARCHAR(255),SPR VARCHAR(255),RSR VARCHAR(255),TSP VARCHAR(255),TSR VARCHAR(255),COP VARCHAR(255),CO2P VARCHAR(255),O2C VARCHAR(255),TOC VARCHAR(255),ARHE VARCHAR(255),Specimenmass VARCHAR(255),Oxygen VARCHAR(255),DPT VARCHAR(255),CO VARCHAR(255),CO2 VARCHAR(255),PDM VARCHAR(255),PDC VARCHAR(255),APT VARCHAR(255),ColdTrapTC VARCHAR(255),StackTC VARCHAR(255),SmokeTC VARCHAR(255),ConeHeaterTC VARCHAR(255),SootMFM VARCHAR(255),SpareTC VARCHAR(255),HFM VARCHAR(255))").arg(baseName));
                QString sql = QStringLiteral("LOAD DATA INFILE '%1' "
                                             "INTO TABLE `%2` "
                                             "CHARACTER SET 'utf8mb4' "
                                             "FIELDS TERMINATED BY ',' "
                                             "ENCLOSED BY '\"' "
                                             "LINES TERMINATED BY '\n' "
                                             "IGNORE 2 ROWS"
                                             "(Test, Content, Time, HRR, EHC, SEA, MLR, SpecificMLR, COY, CO2Y, THR, MFR, k, Vstack, Vsmoke, SPR, RSR, TSP, TSR, COP, CO2P, O2C, TOC, ARHE, Specimenmass, Oxygen, DPT, CO, CO2, PDM, PDC, APT, ColdTrapTC, StackTC, SmokeTC, ConeHeaterTC, SootMFM, SpareTC, HFM);").arg(txtFilePath).arg(baseName);
                if (!query.exec(sql)) {
                    // 处理错误
                    qDebug() << "Error:" << query.lastError().text();
                }else {
                    QMessageBox::information(this,"提示","数据导入完毕");
                    on_pushButton_query_clicked();
                    // 删除文件
                    if (QFile::remove(txtFilePath)) {
                        qDebug() << "文件已删除：" << txtFilePath;
                    } else {
                        qDebug() << "无法删除文件：" << txtFilePath;
                    }
                }
            }else{
                query.exec(QString("CREATE TABLE `%1` (id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,Test VARCHAR(255),Content VARCHAR(255), Time INT,O2 DECIMAL(10,8),DPT DECIMAL(10,2),CO DECIMAL(10,8),CO2 DECIMAL(10,8),PDM DECIMAL(10,6),PDC DECIMAL(10,6),Mass DECIMAL(10,2),Methane_MFM DECIMAL(10,4),APT DECIMAL(10,2),HFM DECIMAL(10,2),Cold_Trap_TC DECIMAL(10,2),Stack_TC DECIMAL(10,2),Smoke_TC DECIMAL(10,2),Cone_Heater_TC DECIMAL(10,2),Spare_TC DECIMAL(10,2),Soot_MFM DECIMAL(10,2),AFM DECIMAL(10,2))").arg(baseName));
                QString sql = QStringLiteral("LOAD DATA INFILE '%1' "
                                             "INTO TABLE `%2` "
                                             "CHARACTER SET 'utf8mb4' "
                                             "FIELDS TERMINATED BY ',' "
                                             "ENCLOSED BY '\"' "
                                             "LINES TERMINATED BY '\n' "
                                             "IGNORE 2 ROWS"
                                             "(Test, Content, Time, O2, DPT, CO, CO2, PDM, PDC, Mass, Methane_MFM, APT, HFM, Cold_Trap_TC, Stack_TC, Smoke_TC, Cone_Heater_TC, Spare_TC, Soot_MFM, AFM);").arg(txtFilePath).arg(baseName);
                // 执行SQL语句
                if (!query.exec(sql)) {
                    // 处理错误
                    qDebug() << "Error:" << query.lastError().text();
                }else {
                    QMessageBox::information(this,"提示","数据导入完毕");
                    on_pushButton_query_clicked();
                    // 删除文件
                    if (QFile::remove(txtFilePath)) {
                        qDebug() << "文件已删除：" << txtFilePath;
                    } else {
                        qDebug() << "无法删除文件：" << txtFilePath;
                    }
                }
            }
        }
    }
    else//不存在，直接创建
    {
        //creatNewTable(work_sheet);
        //InsertData(work_sheet);
        if(red){
            query.exec(QString("CREATE TABLE `%1` (id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,Test VARCHAR(255),Content VARCHAR(255),Time VARCHAR(20),HRR VARCHAR(255),EHC VARCHAR(255),SEA VARCHAR(255),MLR VARCHAR(255),SpecificMLR VARCHAR(255),COY VARCHAR(255),CO2Y VARCHAR(255),THR VARCHAR(255),MFR VARCHAR(255),k VARCHAR(255),Vstack VARCHAR(255),Vsmoke VARCHAR(255),SPR VARCHAR(255),RSR VARCHAR(255),TSP VARCHAR(255),TSR VARCHAR(255),COP VARCHAR(255),CO2P VARCHAR(255),O2C VARCHAR(255),TOC VARCHAR(255),ARHE VARCHAR(255),Specimenmass VARCHAR(255),Oxygen VARCHAR(255),DPT VARCHAR(255),CO VARCHAR(255),CO2 VARCHAR(255),PDM VARCHAR(255),PDC VARCHAR(255),APT VARCHAR(255),ColdTrapTC VARCHAR(255),StackTC VARCHAR(255),SmokeTC VARCHAR(255),ConeHeaterTC VARCHAR(255),SootMFM VARCHAR(255),SpareTC VARCHAR(255),HFM VARCHAR(255))").arg(baseName));
            QString sql = QStringLiteral("LOAD DATA INFILE '%1' "
                                         "INTO TABLE `%2` "
                                         "CHARACTER SET 'utf8mb4' "
                                         "FIELDS TERMINATED BY ',' "
                                         "ENCLOSED BY '\"' "
                                         "LINES TERMINATED BY '\n' "
                                         "IGNORE 2 ROWS"
                                         "(Test, Content, Time, HRR, EHC, SEA, MLR, SpecificMLR, COY, CO2Y, THR, MFR, k, Vstack, Vsmoke, SPR, RSR, TSP, TSR, COP, CO2P, O2C, TOC, ARHE, Specimenmass, Oxygen, DPT, CO, CO2, PDM, PDC, APT, ColdTrapTC, StackTC, SmokeTC, ConeHeaterTC, SootMFM, SpareTC, HFM);").arg(txtFilePath).arg(baseName);
            if (!query.exec(sql)) {
                // 处理错误
                qDebug() << "Error:" << query.lastError().text();
            }else {
                QMessageBox::information(this,"提示","数据导入完毕");
                on_pushButton_query_clicked();
                // 删除文件
                if (QFile::remove(txtFilePath)) {
                    qDebug() << "文件已删除：" << txtFilePath;
                } else {
                    qDebug() << "无法删除文件：" << txtFilePath;
                }
            }
        }else{
            query.exec(QString("CREATE TABLE `%1` (id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,Test VARCHAR(255),Content VARCHAR(255), Time INT,O2 DECIMAL(10,8),DPT DECIMAL(10,2),CO DECIMAL(10,8),CO2 DECIMAL(10,8),PDM DECIMAL(10,6),PDC DECIMAL(10,6),Mass DECIMAL(10,2),Methane_MFM DECIMAL(10,4),APT DECIMAL(10,2),HFM DECIMAL(10,2),Cold_Trap_TC DECIMAL(10,2),Stack_TC DECIMAL(10,2),Smoke_TC DECIMAL(10,2),Cone_Heater_TC DECIMAL(10,2),Spare_TC DECIMAL(10,2),Soot_MFM DECIMAL(10,2),AFM DECIMAL(10,2))").arg(baseName));
            QString sql = QStringLiteral("LOAD DATA INFILE '%1' "
                                         "INTO TABLE `%2` "
                                         "CHARACTER SET 'utf8mb4' "
                                         "FIELDS TERMINATED BY ',' "
                                         "ENCLOSED BY '\"' "
                                         "IGNORE 2 ROWS"
                                         "(Test, Content, Time, O2, DPT, CO, CO2, PDM, PDC, Mass, Methane_MFM, APT, HFM, Cold_Trap_TC, Stack_TC, Smoke_TC, Cone_Heater_TC, Spare_TC, Soot_MFM, AFM);").arg(txtFilePath).arg(baseName);
            // 执行SQL语句
            if (!query.exec(sql)) {
                // 处理错误
                qDebug() << "Error:" << query.lastError().text();
            }else {
                QMessageBox::information(this,"提示","数据导入完毕");
                on_pushButton_query_clicked();
                // 删除文件
                if (QFile::remove(txtFilePath)) {
                    qDebug() << "文件已删除：" << txtFilePath;
                } else {
                    qDebug() << "无法删除文件：" << txtFilePath;
                }
            }
        }
    }
    //    QRegExp rx("([^\/]+)$");//匹配文件路径最后一个"/"的位置
    //    int lastSlashPos = filePath.lastIndexOf('/');
    //    QString fileName;
    //    qDebug() << lastSlashPos <<endl;
    //    if (lastSlashPos != -1) {
    //        fileName = filePath.mid(lastSlashPos + 1);
    //    }// 如果没有找到斜杠，则整个字符串作为文件名
    //    qDebug() << fileName <<endl;

    //    QAxObject *excel = new QAxObject("Excel.Application");
    //    excel->setProperty("Visible", false);// 不显示 Excel 窗体
    //    QAxObject *work_books = excel->querySubObject("WorkBooks"); //获取工作簿集合
    //    work_books->dynamicCall("Open (const QString&)", filePath);//打开已存在的工作簿
    //    QAxObject *work_book = excel->querySubObject("ActiveWorkBook");//获取当前工作簿

    //    QAxObject *work_sheets = work_book->querySubObject("Sheets");  //Sheets也可换用WorkSheets
    //    int sheet_count = work_sheets->property("Count").toInt();  //获取工作表数目
    //    qDebug() << "当前文件有"<<sheet_count<< "张sheet";

    //    for(int i=1; i<=sheet_count; i++)//循环操作每张sheet
    //    {
    //        QAxObject *work_sheet = work_book->querySubObject("Sheets(int)", i);
    //        QString work_sheet_name = work_sheet->property("Name").toString();  //获取工作表名称


    //        //查看数据库中是否有相应表格，没有就创建
    //        if(isTableExists(work_sheet_name))
    //        {
    //            int ok = QMessageBox::warning(this,tr("提示："),tr("当前数据库中已经存在该表，"
    //                                                            "确认替换吗？ "),QMessageBox::Yes,QMessageBox::No);
    //            if(ok == QMessageBox::No);
    //            else  //替换
    //            {
    //                QSqlQuery query(dbMYSQL);
    //                query.exec(QString("drop table if exists %1").arg(work_sheet_name));
    //                creatNewTable(work_sheet);
    //                InsertData(work_sheet);
    //            }
    //        }
    //        else
    //        {
    //            creatNewTable(work_sheet);
    //            InsertData(work_sheet);
    //        }
    //    }
    //    work_book->dynamicCall("Close()");//关闭工作簿
    //    excel->dynamicCall("Quit()");//关闭 excel
    //    delete excel;
    //    excel = NULL;
}

//判断表是否存在,存在为真，不存在为假
bool MainWindow::isTableExists(QString &table)
{
    QSqlQuery query(dbMYSQL);
    QString sql = QString("show tables;");  // 查询数据库中是否存在表名
    query.exec(sql);
    while(query.next())
    {
        QString biaoming=query.value(0).toString().trimmed();
        qDebug()<<"数据库中已存在："<<biaoming;
        if(QString::compare(biaoming,table,Qt::CaseInsensitive));
        else//存在
            return true;
    }
    return false;
}


//在mysql中创建新表格
void MainWindow::creatNewTable(QAxObject *work_sheet)
{
    //获取表头
    QString work_sheet_name = work_sheet->property("Name").toString();  //获取工作表名称
    QAxObject *used_range = work_sheet->querySubObject("UsedRange");//选取当前页面所有已使用单元格
    QAxObject *columns = used_range->querySubObject("Columns");
    int column_start = used_range->property("Column").toInt();  //获取起始列
    int column_count = columns->property("Count").toInt();  //获取列数
    QString keyType[column_count];//表头数列

    for(int i = column_start;i < column_count+column_start;i ++)//获取表头
    {
        QAxObject *cell = work_sheet->querySubObject("Cells(int,int)",1, i);
        QString value = cell->dynamicCall("Value2()").toString();
        keyType[i-column_start] = value;
        qDebug() <<i-column_start<<":"<< keyType[i-column_start];
    }
    QString creatsql=QString("create table %1(").arg(work_sheet_name);//按表头在MySQL中创建新表
    for(int i=0;i<=column_count-1;i++)
    {
        creatsql=creatsql+QString("%1").arg(keyType[i]);
        if(i < column_count-1 )
        {
            creatsql =creatsql+ QString(" varchar(20),");
        }
        else
        {
            creatsql =creatsql+ QString(" varchar(20));");
        }
    }
    qDebug() << creatsql;
    QSqlQuery creatquery(dbMYSQL);
    if(creatquery.exec(creatsql))
        qDebug() << "成功创建表格："<<work_sheet_name;
    else
        qDebug() << "创建表格"<<work_sheet_name<< "失败";
}


//在表格中插入数据
void MainWindow::InsertData(QAxObject *work_sheet)
{
    QString work_sheet_name = work_sheet->property("Name").toString();  //获取工作表名称
    QAxObject *used_range = work_sheet->querySubObject("UsedRange");//选取当前页面所有已使用单元格
    QAxObject *rows = used_range->querySubObject("Rows");
    QAxObject *columns = used_range->querySubObject("Columns");
    int row_start = used_range->property("Row").toInt();  //获取起始行
    int column_start = used_range->property("Column").toInt();  //获取起始列
    int row_count = rows->property("Count").toInt();  //获取行数
    int column_count = columns->property("Count").toInt();  //获取列数
    qDebug() << "column_count:"<<column_count;

    QSqlQuery insertquery(dbMYSQL);
    for(int i = row_start; i < row_count+row_start;i++)//从行开始
    {
        QString strSql = QString("insert into %1 values(").arg(work_sheet_name);
        for(int j = column_start; j < column_count+column_start;j++)
        {
            QAxObject *cell = work_sheet->querySubObject("Cells(int,int)", i+1, j);//去除第一行表头
            QString Value = cell->dynamicCall("Value2()").toString();
            strSql = strSql + QString("'%1'").arg(Value);
            if(j < column_count )
            {
                strSql = strSql + QString(",");
            }
            else
            {
                strSql = strSql + QString(")");
            }
        }
        qDebug()<<strSql;
        //调用写数据函数,将一行数据插入数据库
        insertquery.exec(strSql);
    }

    //验证是否缺少行,不缺少则数据导入成功
    QString resuresql=QString("select count(1) from %1").arg(work_sheet_name);
    insertquery.exec(resuresql);
    insertquery.next();
    if(insertquery.value(0).toInt())
        QMessageBox::warning(this,tr("提示："),tr("数据导入成功"));
    else
        QMessageBox::warning(this,tr("提示："),tr("数据缺失，请重新导入"));
}


void MainWindow::on_pushButton_export_clicked()
{
    QAxObject *excel = new QAxObject("Excel.Application");//创建了一个QAxObject对象，用于访问Excel应用程序的COM接口。
    if (excel->isNull())//判断是否存在excel
    {
        if (excel != NULL)//网络中很多使用 excel==NULL 判断，是错误的
        {
            excel->dynamicCall("Quit()");//关闭
            delete excel;
        }
        QMessageBox::critical(0, "错误信息", "没有找到 EXCEL 应用程序");
        return;
    }
    QAxObject *workbooks = NULL;
    QAxObject *workbook = NULL;
    QAxObject *worksheets = NULL;
    QAxObject *worksheet = NULL;
    excel->dynamicCall("SetVisible (bool)", true);//不显示窗体
    excel->setProperty("DisplayAlerts", false); //不显示任何警告信息。如果为 true 那么在关闭是会出现类似“文件已修改，是否保存” 的提示
    workbooks = excel->querySubObject("WorkBooks");//获取工作簿集合
    QString filePath = QFileDialog::getSaveFileName(this, tr("Save File"),"",tr("Excel Files (*.xlsx *.xls)"));
    if (QFile::exists(filePath))
    {
        workbook = workbooks->querySubObject("Open(const QString &)", filePath);
    }
    else
    {
        workbooks->dynamicCall("Add");//新建一个工作簿
        workbook = excel->querySubObject("ActiveWorkBook");//获取当前工作簿
    }
    worksheets = workbook->querySubObject("Sheets");//获取工作表集合
    worksheet = worksheets->querySubObject("Item(int)",1);//获取工作表集合的工作表 1，即sheet1
    QAxObject * usedrange = worksheet->querySubObject("UsedRange");//获取该 sheet 的使用范围对象
    QAxObject * rows = usedrange->querySubObject("Rows");
    QAxObject * columns = usedrange->querySubObject("Columns");
    int intRowStart = usedrange->property("Row").toInt();
    int intColStart = usedrange->property("Column").toInt();
    int intCols = columns->property("Count").toInt();
    int intRows = rows->property("Count").toInt();
    QAxObject *cell = NULL;
    int rowCount = ui->tableView->model()->rowCount();
    int colCount = ui->tableView->model()->columnCount();

    // 获取表头信息
    QStandardItemModel *model = qobject_cast<QStandardItemModel*>(ui->tableView->model());
    QList<QStandardItem*> headers;
    for(int column = 0; column < model->columnCount(); ++column) {
        headers.append(model->horizontalHeaderItem(column));
    }

    // 清空数据
    for(int i=intRowStart;i <intRowStart + intRows;i++)
    {
        for(int j=intColStart ;j<intColStart+intCols;j++)
        {
            cell = worksheet->querySubObject("Cells(int,int)", i,j ); //获取单元格
            cell->setProperty("Value", "");
        }
    }

    // 插入表头数据到Excel的第一行
    for(int j = intColStart; j < intColStart + colCount; j++)
    {
        QModelIndex headerIndex = model->index(0, j-intColStart);
        QVariant headerData = model->headerData(j-intColStart, Qt::Horizontal);
        cell = worksheet->querySubObject("Cells(int,int)", intRowStart, j);
        cell->setProperty("Value", headerData.toString());
    }

    // 插入数据
    for (int i = intRowStart + 1; i < intRowStart+rowCount+1; i++)
    {
        for(int j = intColStart; j < intColStart+colCount; j++)
        {
            QModelIndex indextemp = ui->tableView->model()->index(i-intRowStart-1, j-intColStart);
            QVariant str = ui->tableView->model()->data(indextemp);
            cell = worksheet->querySubObject("Cells(int,int)", i, j);//获取单元格
            cell->setProperty("Value", str);
        }
    }
    QMessageBox::information(this,"提示","数据导出完毕");
    workbook->dynamicCall("SaveAs(const QString&)",QDir::toNativeSeparators(filePath));//保存至 filepath，注意一定要用 QDir::toNativeSeparators 将路径中的"/"转换为"\"，不然一定保存不了。
    qDebug() <<"保存路径为："<< QDir::toNativeSeparators(filePath);
    workbook->dynamicCall("Close()");//关闭工作簿
    excel->dynamicCall("Quit()");//关闭 excel
    delete excel;
    excel = NULL;
}

void MainWindow::on_pushButton_modify_clicked()
{
    if(login::userType!="User")
    {
        ui->tableView->setEditTriggers(QAbstractItemView::DoubleClicked);//设置为双击可修改
        int rowNum = mymodel->rowCount(); //获得表的行数
        int id = rowNum+1;
        mymodel->insertRow(rowNum); //添加一行
        mymodel->setData(mymodel->index(rowNum,0),id);
    //    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);//设置为双击可修改
    }
    else
        QMessageBox::warning(this,tr("提示："),tr("您没有权限进行此操作"));
}


void MainWindow::on_pushButton_removecurves_clicked()
{
    lineNumber=0;
    ui->customPlot->clearGraphs();//清空所有曲线
    ui->customPlot->legend->setVisible(false);//取消图例
    ui->customPlot->replot();   //刷新图表
}

void MainWindow::on_pushButton_admin_clicked()
{
    if(login::userType=="User")
        QMessageBox::warning(this,tr("提示："),tr("您没有权限进行此操作"));
    else if(login::userType=="Administrator")
    {

    }
}
//返回home界面
void MainWindow::on_pushButton_home_clicked()
{
    database_home *dw = new database_home();
    //emit valueChanged(true);
    //MainWindow *w = new MainWindow();
    //connect(this,&MainWindow::valueChanged,dw,&database_home::setValue);
    dw->setValue(true, "yr");
    this->hide();
    dw->setWindowTitle("森林-城镇交界域典型建筑材料的引燃和燃烧危险性数据库");
    dw->show();
}
//弹出csv文件左两列的相关数据
void MainWindow::on_pushButton_testvalue_clicked()
{
    showWidget = new QWidget();
    QVBoxLayout *layout = new QVBoxLayout(showWidget);
    //delete tdmodel;
    tdmodel = new QStandardItemModel(showWidget);
    //delete tableview;
    tableview = new QTableView(showWidget);
    parameterBtn = new QPushButton(tr("重要参数"));

    QString itemText;
    for(int i =0; i < ui->treeWidget->topLevelItemCount(); i++ ){
        QTreeWidgetItem *topLevelItem = ui->treeWidget->topLevelItem(i);
        if(topLevelItem->checkState(0)){
            itemText = topLevelItem->text(0);
        }
    }
    qDebug()<<itemText;
    QString filtersql="select `%1`.`Test`,`%1`.`Content`  from `%1`";//筛选结果

    QSqlQuery query(dbMYSQL);
    int space = 0;
    QStandardItem *item1;
    QStandardItem *item2;
    if(query.exec(filtersql.arg(itemText))){
        items1.clear();
        items2.clear();
        while (query.next()) {
            if(query.value(0).toString() == NULL && query.value(1).toString() == NULL){
                space++;
            }else{
                space = 0;
            }
            if(space < 12){
                item1 = new QStandardItem(query.value(0).toString());
                items1 << item1;
                item2 = new QStandardItem(query.value(1).toString());
                items2 << item2;
            }else{
                break;
            }
        }
        tdmodel->appendColumn(items1);
        tdmodel->appendColumn(items2);
    }else{
        qDebug() << "Query failed:" << query.lastError();
    }
    QStringList headers;
    headers << "基本信息" << "参数";
    tdmodel->setHorizontalHeaderLabels(headers);

    tableview->setModel(tdmodel);
    tableview->resizeColumnsToContents();

    layout->addWidget(tableview);
    layout->addWidget(parameterBtn);
    connect(parameterBtn,&QPushButton::clicked,this,&MainWindow::on_parameterBtn_clicked);
    showWidget->setWindowTitle("信息展示窗口");
    showWidget->setLayout(layout);

    // 获取QTableView的所需宽度
    int tableViewWidth = tableview->horizontalHeader()->length() * 1.13 + tableview->frameWidth() * 2;
    // 设置QWidget的最小宽度
    showWidget->setMinimumWidth(tableViewWidth);
    showWidget->setMinimumHeight(tableViewWidth * 1.2);
    //showWidget->setGeometry(QRect(500, 500, 800, 1200));

    // 获取主屏幕的几何信息
    QRect screenGeometry = QApplication::desktop()->screenGeometry();

    // 计算窗口居中时左上角的坐标
    int x = (screenGeometry.width() - tableViewWidth) / 2;
    int y = (screenGeometry.height() - tableViewWidth * 1.2) / 2;

    // 设置窗口居中显示
    showWidget->move(x, y);

    showWidget->setStyleSheet(tr("QTableView::item:hover{background-color: rgb(30,30,30);font: 75 9pt 'Microsoft YaHei';color:rgb(31,163,246);}"));
    showWidget->show();

}


void MainWindow::on_toolButton_clicked()
{
    QString search = ui->lineEdit->text();
    qDebug()<<"search line:"<<search;

    for (int i = 0; i < ui->treeWidget->topLevelItemCount(); ++i) {
        QTreeWidgetItem* parentItem = ui->treeWidget->topLevelItem(i);
        // 检查父节点的第一个子节点的文本是否与目标字符串匹配
        if (parentItem->text(0).contains(search,Qt::CaseInsensitive)) {
            // 保留匹配的父节点及其所有子节点
            // 由于我们要保留整个分支，所以这里不需要做任何操作
        } else {
            // 隐藏不匹配的父节点及其所有子节点
            parentItem->setHidden(true);
            // 遍历所有子节点并隐藏它们
            for (int j = 0; j < parentItem->childCount(); ++j) {
                QTreeWidgetItem* childItem = parentItem->child(j);
                childItem->setHidden(true);
            }
        }
    }
    // ui->treeWidget->expandToDepth(1);
}

void MainWindow::on_parameterBtn_clicked()
{
    paraWidget = new QWidget();
    paraWidget->setWindowTitle(tr("材料燃烧特性重要参数"));

    QMap<QString,QString> paraMap;
    paraMap = {{"点燃时间(s)","Time to ignition"},{"最大热释放速率(kW/m2)","peak HRR"},{"最大有效燃烧热(MJ/kg)","peak EHC"},{"最大质量损失速率(g/s)","peak MLR"},{"最大比消光面积(m2/kg)","peak SEA"},{"最大CO生成率(kg/kg)","peak COY"},{"最大CO2生成率(kg/kg)","peak CO2Y"},
               {"达到最大热释放速率的时间(s)","t peak HRR"},{"达到最大有效燃烧热的时间(s)","t peak EHC"},{"达到最大质量损失的时间(s)","t peak MLR"},{"达到最大比消光面积的时间(s)","t peak SEA"},{"达到最大CO生成率的时间(s)","t peak COY"},{"达到最大CO2生成率的时间(s)","t peak CO2Y"},
               {"总热释热量(MJ/m2)","Total heat release"},{"总耗氧量(g)","Total oxygen consumed"},{"质量损失(g)","Mass lost"},{"质量损失速率(g/s)","Average specific MLR"},{"总烟气释放量(m2/m2)","Total smoke release"},{"总产烟量(m2)","Total smoke production"}};
    QList<QString> paralist = {"点燃时间(s)","最大热释放速率(kW/m2)","最大有效燃烧热(MJ/kg)","最大质量损失速率(g/s)","最大比消光面积(m2/kg)","最大CO生成率(kg/kg)","最大CO2生成率(kg/kg)",
                               "达到最大热释放速率的时间(s)","达到最大有效燃烧热的时间(s)","达到最大质量损失的时间(s)","达到最大比消光面积的时间(s)","达到最大CO生成率的时间(s)","达到最大CO2生成率的时间(s)",
                               "总热释热量(MJ/m2)","总耗氧量(g)","质量损失(g)","质量损失速率(g/s)","总烟气释放量(m2/m2)","总产烟量(m2)"};
    QMap<QString,QString> paraMapRe;
    for (auto it = paraMap.begin(); it != paraMap.end(); ++it) {
            paraMapRe.insert(it.value(),it.key());
    }
    //qDebug()<<"交换前的paraMap: "<<paraMap;
    qDebug()<<"交换后的paramapre: "<<paraMapRe;

    QList<QStandardItem*>::iterator it = items1.begin();
    QList<QStandardItem*>::iterator itv = items2.begin();
    for( ; it != items1.end() ; ++it,++itv )
    {
        QStandardItem *item = *it;
        QStandardItem *itemv = *itv;
        QMapIterator<QString,QString> para(paraMapRe);
        while(para.hasNext()){
            para.next();
            if(item->text().contains(para.key(),Qt::CaseInsensitive))
            {
                paraMapRe[para.key()] = itemv->text();
            }
        }
    }
    QMap<QString,QString> paraFinal;
    foreach(const QString &key,paraMap.keys())
    {
        if(paraMapRe.contains(paraMap.value(key)))
        {
            paraFinal[key] = paraMapRe.find(paraMap.value(key)).value();
        }
    }
    qDebug()<<"最终的paraFinal: "<<paraFinal;

    QVBoxLayout *layout = new QVBoxLayout(paraWidget);
    paramodel = new QStandardItemModel(paraWidget);
    ptableview = new QTableView(paraWidget);

    QStandardItem *item1;
    QStandardItem *item2;

    pitems1.clear();
    pitems2.clear();

    QList<QString>::iterator it1 = paralist.begin();
    for(; it1!=paralist.end(); ++it1)
    {
        item1 = new QStandardItem(*it1);
        pitems1 << item1;
        if(paraFinal.contains(*it1)){
            item2 = new QStandardItem(paraFinal.find(*it1).value());
            pitems2 << item2;
        }
    }
    paramodel->appendColumn(pitems1);
    paramodel->appendColumn(pitems2);
    QStringList headers;
    headers << "重要属性" << "参数";
    paramodel->setHorizontalHeaderLabels(headers);

    ptableview->setModel(paramodel);
    ptableview->resizeColumnsToContents();
    layout->addWidget(ptableview);
    paraWidget->setLayout(layout);
    // 获取QTableView的所需宽度
    int tableViewWidth = ptableview->horizontalHeader()->length() * 1.25 + ptableview->frameWidth() * 2;
    // 设置QWidget的最小宽度
    paraWidget->setMinimumWidth(tableViewWidth);
    paraWidget->setMinimumHeight(tableViewWidth * 1.2);
    //showWidget->setGeometry(QRect(500, 500, 800, 1200));
    paraWidget->setStyleSheet(tr("QTableView::item:hover{background-color: rgb(30,30,30);font: 75 9pt 'Microsoft YaHei';color:rgb(31,163,246);}"));

    paraWidget->show();
}

void MainWindow::on_pushButton_10_clicked()
{
    lineNumber=0;

    ui->customPlot->clearGraphs();//清空所有曲线
    ui->customPlot->legend->setVisible(false);//取消图例
    ui->customPlot->replot();   //刷新图表

    for (int i = 0; i < ui->treeWidget->topLevelItemCount(); ++i)
    {
        QTreeWidgetItem *topLevelItem = ui->treeWidget->topLevelItem(i);
        topLevelItem->setCheckState(0, Qt::Unchecked);
        for (int j = 0; j < topLevelItem->childCount(); ++j)
        {
            QTreeWidgetItem *childItem = topLevelItem->child(j);
            childItem->setCheckState(0, Qt::Unchecked);
        }
    }
}

